<!-- 租户管理 -->
<template>
  <div class="process-container">
    <div class="table__wrapper">
      <transition :enter-active-class="this.animate.searchAnimate.enter" :leave-active-class="this.animate.searchAnimate.leave">
        <div class="search" v-show="showSearch">
          <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" label-width="68px">
              <el-form-item label="租户编号" prop="tenantId">
                <el-input v-model="queryParams.tenantId" placeholder="请输入租户编号" clearable style="width: 240px" @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="联系人" prop="contactUserName">
                <el-input v-model="queryParams.contactUserName" placeholder="请输入联系人" clearable style="width: 240px" @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="联系电话" prop="contactPhone">
                <el-input v-model="queryParams.contactPhone" placeholder="请输入联系电话" clearable style="width: 240px" @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="企业名称" prop="companyName">
                <el-input v-model="queryParams.companyName" placeholder="请输入企业名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
        </div>
      </transition>
      <div class="table-operates">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAdd" v-hasPermi="['system:tenant:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" size="mini" icon="el-icon-edit-outline" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:tenant:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" size="mini" icon="el-icon-delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:tenant:remove']">
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" size="mini" icon="el-icon-download" @click="handleExport" v-hasPermi="['system:tenant:export']">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </div>
      <el-table v-loading="loading" :data="tenantList" height="100%" @selection-change="handleSelectionChange" class="common-table">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="id" align="center" prop="id" v-if="false" />
        <el-table-column label="租户编号" align="center" prop="tenantId" />
        <el-table-column label="联系人" align="center" prop="contactUserName" />
        <el-table-column label="联系电话" align="center" prop="contactPhone" />
        <el-table-column label="企业名称" align="center" prop="companyName" />
        <el-table-column label="社会信用代码" align="center" prop="licenseNumber" />
        <el-table-column label="过期时间" align="center" prop="expireTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.expireTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="租户状态" align="center" prop="status">
          <template #default="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column width="150" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button type="text" icon="el-icon-edit-outline" @click="handleUpdate(scope.row)" v-hasPermi="['system:tenant:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="同步套餐" placement="top">
              <el-button type="text" icon="el-icon-refresh" @click="handleSyncTenantPackage(scope.row)" v-hasPermi="['system:tenant:edit']">
              </el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:tenant:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </div>
    <!-- 添加或修改租户对话框 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.visible" width="500px" append-to-body>
      <el-form ref="tenantFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="企业名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入企业名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactUserName">
          <el-input v-model="form.contactUserName" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item v-if="!form.id" label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入系统用户名" maxlength="30" />
        </el-form-item>
        <el-form-item v-if="!form.id" label="用户密码" prop="password">
          <el-input type="password" v-model="form.password" placeholder="请输入系统用户密码" maxlength="20" />
        </el-form-item>
        <el-form-item label="租户套餐" prop="packageId">
          <!-- !!form.tenantId  -->
          <el-select v-model="form.packageId" :disabled="form.tenantId === '000000'" placeholder="请选择租户套餐" clearable style="width: 100%">
            <el-option v-for="item in packageList" :key="item.packageId" :label="item.packageName" :value="item.packageId" />
          </el-select>
        </el-form-item>
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker clearable v-model="form.expireTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择过期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="用户数量" prop="accountCount">
          <el-input v-model="form.accountCount" placeholder="请输入用户数量" />
        </el-form-item>
        <el-form-item label="绑定域名" prop="domain">
          <el-input v-model="form.domain" placeholder="请输入绑定域名" />
        </el-form-item>
        <el-form-item label="企业地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入企业地址" />
        </el-form-item>
        <el-form-item label="企业代码" prop="licenseNumber">
          <el-input v-model="form.licenseNumber" placeholder="请输入统一社会信用代码" />
        </el-form-item>
        <el-form-item label="企业简介" prop="intro">
          <el-input type="textarea" v-model="form.intro" placeholder="请输入企业简介" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listTenant, getTenant, delTenant, addTenant, updateTenant, changeTenantStatus, syncTenantPackage } from '@/api/system/tenant';
import { selectTenantPackage } from '@/api/system/tenantPackage';


const initFormData = {
  id: undefined,
  tenantId: undefined,
  contactUserName: '',
  contactPhone: '',
  username: '',
  password: '',
  companyName: '',
  licenseNumber: '',
  domain: '',
  address: '',
  intro: '',
  remark: '',
  packageId: '',
  expireTime: '',
  accountCount: 0,
  status: '0',
}
export default {
  name: "Tenant",
  //import引入的组件需要注入到对象中才能使用
  components: {
    
  },
  data() {
      //这里存放数据
      return {
        tenantList:[],
        packageList:[],
        buttonLoading:false,
        loading:true,
        showSearch:true,
        ids: [],
        single:true,
        multiple: true,
        total:0,
        dialog: {
          visible: false,
          title: ''
        },
        form: { ...initFormData },
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          tenantId: '',
          contactUserName: '',
          contactPhone: '',
          companyName: ''
        },
        rules: {
          id: [{ required: true, message: "id不能为空", trigger: "blur" }],
          tenantId: [{ required: true, message: "租户编号不能为空", trigger: "blur" }],
          contactUserName: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
          contactPhone: [{ required: true, message: "联系电话不能为空", trigger: "blur" }],
          companyName: [{ required: true, message: "企业名称不能为空", trigger: "blur" }],
          username: [
            { required: true, message: "用户名不能为空", trigger: "blur" },
            { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
          ],
          password: [
            { required: true, message: "密码不能为空", trigger: "blur" },
            { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
          ]
        }
      };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {

  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getList()
  },
  //方法集合
  methods: {
    /** 查询所有租户套餐 */
    async getTenantPackage() {
      const res = await selectTenantPackage()
      this.packageList = res.data;
    },

    /** 查询租户列表 */
    async getList(){
      this.loading = true;
      const res = await listTenant(this.queryParams);
      this.tenantList = res.rows;
      this.total = res.total;
      this.loading = false;
    },

    // 租户套餐状态修改
    async handleStatusChange(row){
      let text = row.status === "0" ? "启用" : "停用";
      try {
        await this.$modal.confirm('确认要"' + text + '""' + row.companyName + '"租户吗？');
        await changeTenantStatus(row.id, row.tenantId, row.status);
        this.$modal.msgSuccess(text + "成功");
      } catch {
        row.status = row.status === "0" ? "1" : "0";
      }
    },

    // 取消按钮
    cancel() {
      this.reset();
      this.dialog.visible = false;
    },

    // 表单重置
    reset() {
      this.form = { ...initFormData };
      this.$refs.tenantFormRef && this.$refs.tenantFormRef.resetFields();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryFormRef.resetFields();
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTenantPackage();
      this.dialog.visible = true;
      this.dialog.title = "添加租户";
    },

    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      await this.getTenantPackage();
      const _id = row?.id || this.ids[0];
      const res = await getTenant(_id);
      Object.assign(this.form, res.data)
      this.dialog.visible = true;
      this.dialog.title = "修改租户";
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs.tenantFormRef.validate(async (valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id) {
            await updateTenant(this.form).finally(() => this.buttonLoading = false);
          } else {
            await addTenant(this.form).finally(() => this.buttonLoading = false);
          }
          this.$modal.msgSuccess("操作成功");
          this.dialog.visible = false;
          await this.getList();
        }
      });
    },

    /** 删除按钮操作 */
    async handleDelete (row) {
      const _ids = row?.id || this.ids;
      await this.$modal.confirm('是否确认删除租户编号为"' + _ids + '"的数据项？')
      this.loading = true;
      await delTenant(_ids).finally(() => this.loading = false);
      await this.getList();
      this.$modal.msgSuccess("删除成功");


    },

    /** 同步租户套餐按钮操作 */
    async handleSyncTenantPackage(row){
      try {
        await this.$modal.confirm('是否确认同步租户套餐租户编号为"' + row.tenantId + '"的数据项？');
        this.loading = true;
        await syncTenantPackage(row.tenantId, row.packageId);
        await this.getList();
        this.$modal.msgSuccess("同步成功");
      } catch { return } finally {
        this.loading = false;
      }
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('system/tenant/export', {
        ...this.queryParams
      }, `tenant_${new Date().getTime()}.xlsx`)
    },
  },
}
</script>
